<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang>
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="数据结构,算法,栈与队列,">





  <link rel="alternate" href="/blog/atom.xml" title="编程那点事" type="application/atom+xml">






<meta name="description" content="学习JavaScript数据结构与算法（一）：栈与队列学习JavaScript数据结构与算法（二）：链表学习JavaScript数据结构与算法（三）：集合学习JavaScript数据结构与算法（四）：二叉搜索树  学习起因曾经有一次在逛V2EX时，碰到这么一个帖子。  数学完全还给老师了，想学回一些基础数学，大概是高中程度的，有什么书籍推荐？  发帖的楼主大学没有高数课程，出去工作时一直在从事前">
<meta name="keywords" content="数据结构,算法,栈与队列">
<meta property="og:type" content="article">
<meta property="og:title" content="学习JavaScript数据结构与算法（一）：栈与队列">
<meta property="og:url" content="https://lhweb.gitee.io/blog/2018/09/23/学习JavaScript数据结构与算法（一）：栈与队列/index.html">
<meta property="og:site_name" content="编程那点事">
<meta property="og:description" content="学习JavaScript数据结构与算法（一）：栈与队列学习JavaScript数据结构与算法（二）：链表学习JavaScript数据结构与算法（三）：集合学习JavaScript数据结构与算法（四）：二叉搜索树  学习起因曾经有一次在逛V2EX时，碰到这么一个帖子。  数学完全还给老师了，想学回一些基础数学，大概是高中程度的，有什么书籍推荐？  发帖的楼主大学没有高数课程，出去工作时一直在从事前">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://lhweb.gitee.io/blog/2018/09/23/学习JavaScript数据结构与算法（一）：栈与队列/ds.png">
<meta property="og:image" content="https://lhweb.gitee.io/blog/2018/09/23/学习JavaScript数据结构与算法（一）：栈与队列/stack.jpg">
<meta property="og:updated_time" content="2019-10-03T05:53:45.945Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="学习JavaScript数据结构与算法（一）：栈与队列">
<meta name="twitter:description" content="学习JavaScript数据结构与算法（一）：栈与队列学习JavaScript数据结构与算法（二）：链表学习JavaScript数据结构与算法（三）：集合学习JavaScript数据结构与算法（四）：二叉搜索树  学习起因曾经有一次在逛V2EX时，碰到这么一个帖子。  数学完全还给老师了，想学回一些基础数学，大概是高中程度的，有什么书籍推荐？  发帖的楼主大学没有高数课程，出去工作时一直在从事前">
<meta name="twitter:image" content="https://lhweb.gitee.io/blog/2018/09/23/学习JavaScript数据结构与算法（一）：栈与队列/ds.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://lhweb.gitee.io/blog/2018/09/23/学习JavaScript数据结构与算法（一）：栈与队列/">





  <title>学习JavaScript数据结构与算法（一）：栈与队列 | 编程那点事</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">编程那点事</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://lhweb.gitee.io/blog/blog/2018/09/23/学习JavaScript数据结构与算法（一）：栈与队列/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="lhweb">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="编程那点事">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">学习JavaScript数据结构与算法（一）：栈与队列</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-09-23T16:55:30+08:00">
                2018-09-23
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/javascript/" itemprop="url" rel="index">
                    <span itemprop="name">javascript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p><a href="https://lhweb.gitee.io/blog/2018/09/23/%E5%AD%A6%E4%B9%A0JavaScript%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95%EF%BC%88%E4%B8%80%EF%BC%89%EF%BC%9A%E6%A0%88%E4%B8%8E%E9%98%9F%E5%88%97/">学习JavaScript数据结构与算法（一）：栈与队列</a><br><a href="https://lhweb.gitee.io/blog/2018/09/23/%E5%AD%A6%E4%B9%A0JavaScript%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95%EF%BC%88%E4%BA%8C%EF%BC%89%EF%BC%9A%E9%93%BE%E8%A1%A8/">学习JavaScript数据结构与算法（二）：链表</a><br><a href="https://lhweb.gitee.io/blog/2018/09/23/%E5%AD%A6%E4%B9%A0JavaScript%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95%EF%BC%88%E4%B8%89%EF%BC%89%EF%BC%9A%E9%9B%86%E5%90%88/">学习JavaScript数据结构与算法（三）：集合</a><br><a href="https://lhweb.gitee.io/blog/2018/09/23/%E5%AD%A6%E4%B9%A0JavaScript%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95%EF%BC%88%E5%9B%9B%EF%BC%89%EF%BC%9A%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91/">学习JavaScript数据结构与算法（四）：二叉搜索树</a></p>
</blockquote>
<h1 id="学习起因"><a href="#学习起因" class="headerlink" title="学习起因"></a>学习起因</h1><p>曾经有一次在逛V2EX时，碰到这么一个帖子。</p>
<blockquote>
<p>数学完全还给老师了，想学回一些基础数学，大概是高中程度的，有什么书籍推荐？</p>
</blockquote>
<p>发帖的楼主大学没有高数课程，出去工作时一直在从事前端的工作。感觉到数学知识的匮乏，所以想补一补数学。<br>看了看帖子，感觉和我很像，因为我的专业是不开高数的，我学的也是前端。也同样感觉到了数学知识匮乏所带来的困顿。同时因为自己的数学思维实在是不怎么好，所以决定努力补习数学与计算机基础知识。</p>
<p>当时也有人说:”前端需要什么数据结构与算法”，但是对于这个事情我有自己的看法。</p>
<blockquote>
<p>我并不认为前端不需要算法之类的知识，在我看来前端具备坚实的计算机基础，对自身发展是极其有利的。我想做程序员。而不是一辈子的初级前端和码农。</p>
</blockquote>
<p>也算是给自己的勉励吧。毕竟基础决定上限，再加上自己对计算机真的很感兴趣，所以学起来就算很累，但也是很幸福的。于是去网上选购了《学习JavaScript数据结构与算法》这本书，配合着去图书馆借阅的《大话数据结构》，开始了数据结构与算法的初步学习。</p>
<p><img src="/blog/2018/09/23/学习JavaScript数据结构与算法（一）：栈与队列/ds.png" alt></p>
<p>这本书讲的内容很是不错，清晰易懂。同时用JavaScipt语言实现，学起来的难度低。值得一看呢。</p>
<h1 id="栈"><a href="#栈" class="headerlink" title="栈"></a>栈</h1><p>书中前两章是对JavaScipt基础与数组常用操作的讲解，如果不清楚的话,推荐去看看下面这篇博客。</p>
<p><a href="https://lhweb.gitee.io/blog/2018/09/23/javascript%E4%B9%8B%E6%95%B0%E7%BB%84%E6%93%8D%E4%BD%9C/">JavaScipt之数组操作</a></p>
<p>接下来就是数据结构的第一部分，栈。</p>
<p>栈是一种遵从后进先出原则(LIFO,全称为Last In First Out)的有序集合。栈顶永远是最新的元素。<br>举个例子就是:栈就像放在箱子里的一叠书 你要拿下面的书先要把上面的书拿开。(当然，你不能先拿下面的书。)<br>看图示也可明白。</p>
<p><img src="/blog/2018/09/23/学习JavaScript数据结构与算法（一）：栈与队列/stack.jpg" alt></p>
<h2 id="JavaScipt中栈的实现"><a href="#JavaScipt中栈的实现" class="headerlink" title="JavaScipt中栈的实现"></a>JavaScipt中栈的实现</h2><p>首先，创建一个构造函数。<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 栈的构造函数</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Stack</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 用数组来模拟栈</span></span><br><span class="line">  <span class="keyword">var</span> item = [];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>栈需要有如下的方法:</p>
<ul>
<li><p>push(element(s)): 添加几个元素到栈顶</p>
</li>
<li><p>pop(): 移除并返回栈顶元素</p>
</li>
<li><p>peek(): 返回栈顶元素</p>
</li>
<li><p>isAmpty: 检查栈是否为空，为空则返回true</p>
</li>
<li><p>clear: 移除栈中所有元素</p>
</li>
<li><p>size: 返回栈中元素个数。</p>
</li>
<li><p>print: 以字符串显示栈中所有内容</p>
</li>
</ul>
<h3 id="push方法的实现"><a href="#push方法的实现" class="headerlink" title="push方法的实现"></a>push方法的实现</h3><p>说明: 需要往栈中添加新元素，元素位置在队列的末尾。也就是说，我们可以用数组的push方法来模拟实现。<br>实现:<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 将元素送入栈，放置于数组的最后一位</span></span><br><span class="line"><span class="comment"> * @param  &#123;Any&#125; element 接受的元素，不限制类型</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.push = <span class="function"><span class="keyword">function</span><span class="params">(element)</span> </span>&#123;</span><br><span class="line">  items.push(element);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h3 id="pop方法的实现"><a href="#pop方法的实现" class="headerlink" title="pop方法的实现"></a>pop方法的实现</h3><p>说明: 需要把栈顶元素弹出，同时返回被弹出的值。可以用数组的pop方法来模拟实现。<br>实现:<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 弹出栈顶元素</span></span><br><span class="line"><span class="comment"> * @return &#123;Any&#125; 返回被弹出的值</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.pop = <span class="function"><span class="keyword">function</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> items.pop();</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h3 id="peek方法的实现"><a href="#peek方法的实现" class="headerlink" title="peek方法的实现"></a>peek方法的实现</h3><p>说明: 查看栈顶元素，可以用数组长度来实现。<br>实现:<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 查看栈顶元素</span></span><br><span class="line"><span class="comment"> * @return &#123;Any&#125; 返回栈顶元素</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.peek = <span class="function"><span class="keyword">function</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> items[items.length - <span class="number">1</span>];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="其余方法的实现"><a href="#其余方法的实现" class="headerlink" title="其余方法的实现"></a>其余方法的实现</h3><p>说明: 前三个是栈方法的核心，其余方法则在此一次性列出。因为下文要讲的队列，会与这部分有很大重合。<br>实现:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 确定栈是否为空</span></span><br><span class="line"><span class="comment"> * @return &#123;Boolean&#125; 若栈为空则返回true,不为空则返回false</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.isAmpty = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> items.length === <span class="number">0</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 清空栈中所有内容</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.clear = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  items = [];</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 返回栈的长度</span></span><br><span class="line"><span class="comment"> * @return &#123;Number&#125; 栈的长度</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.size = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> items.length;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 以字符串显示栈中所有内容</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.print = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(items.toString());</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h2 id="实际应用"><a href="#实际应用" class="headerlink" title="实际应用"></a>实际应用</h2><p>栈的实际应用比较多，书中有个十进制转二进制的函数。(不懂二进制怎么算的话可以百度)下面是函数的源代码。<br>原理就是输入要转换的数字，不断的除以二并取整。并且最后运用while循环，将栈中所有数字拼接成字符串输出。<br><figure class="highlight maxima"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 将10进制数字转为2进制数字</span></span><br><span class="line"><span class="comment"> * @param  &#123;Number&#125; decNumber 要转换的10进制数字</span></span><br><span class="line"><span class="comment"> * @return &#123;Number&#125;           转换后的2进制数字</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">function divideBy2(decNumber) &#123;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">var</span> remStack = <span class="built_in">new</span> Stack(),</span><br><span class="line">    <span class="built_in">rem</span>,</span><br><span class="line">    binaryString = '';</span><br><span class="line"></span><br><span class="line">  <span class="keyword">while</span> (decNumber &gt; <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="built_in">rem</span> = Math.<span class="built_in">floor</span>(decNumber <span class="symbol">%</span> <span class="number">2</span>);</span><br><span class="line">    remStack.<span class="built_in">push</span>(<span class="built_in">rem</span>);</span><br><span class="line">    decNumber = Math.<span class="built_in">floor</span>(decNumber / <span class="number">2</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">while</span> (!remStack.isAmpty()) &#123;</span><br><span class="line">    binaryString += remStack.<span class="built_in">pop</span>().toString();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">return</span> binaryString;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h1 id="队列"><a href="#队列" class="headerlink" title="队列"></a>队列</h1><p>队列与栈是很相像的数据结构，不同之处在于队列是是先进先出(FIFO:First In First Out)的。<br>举个例子: 火车站排队买票，先到的先买。(插队的不算)，是不是很好理解了~</p>
<h2 id="JavaScipt中队列的实现"><a href="#JavaScipt中队列的实现" class="headerlink" title="JavaScipt中队列的实现"></a>JavaScipt中队列的实现</h2><p>队列的实现和栈很像。首先依然是构造函数:<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 队列构造函数</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Queue</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> items = [];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>队列需要有如下的方法:</p>
<ul>
<li><p>enqueue(element(s)): 向队列尾部添加几个项</p>
</li>
<li><p>dequeue(): 移除队列的第一项(也就是排在最前面的项)</p>
</li>
<li><p>front(): 返回队列的第一个元素，也就是最新添加的那个</p>
</li>
</ul>
<p>其余方法与队列相同</p>
<h3 id="enqueue方法的实现"><a href="#enqueue方法的实现" class="headerlink" title="enqueue方法的实现"></a>enqueue方法的实现</h3><p>说明: 向队列尾部添加几个项。<br>实现:<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 将元素推入队列尾部</span></span><br><span class="line"><span class="comment"> * @param  &#123;Any&#125; ele 要推入队列的元素</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.enqueue = <span class="function"><span class="keyword">function</span><span class="params">(ele)</span> </span>&#123;</span><br><span class="line">  items.push(ele);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h3 id="dequeue方法的实现"><a href="#dequeue方法的实现" class="headerlink" title="dequeue方法的实现"></a>dequeue方法的实现</h3><p>说明: 移除队列的第一项。<br>实现:<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 将队列中第一个元素弹出</span></span><br><span class="line"><span class="comment"> * @return &#123;Any&#125; 返回被弹出的元素</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.dequeue = <span class="function"><span class="keyword">function</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> items.shift()</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h3 id="front方法的实现"><a href="#front方法的实现" class="headerlink" title="front方法的实现"></a>front方法的实现</h3><p>说明: 返回队列的第一个元素，也就是最新添加的那个。<br>实现:<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 查看队列的第一个元素</span></span><br><span class="line"><span class="comment"> * @return &#123;Any&#125; 返回队列中第一个元素</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.front = <span class="function"><span class="keyword">function</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> items[<span class="number">0</span>];</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>以上的三个方法，就是队列这种数据结构的核心方法了。其实很好理解的。</p>
<h2 id="实际应用-1"><a href="#实际应用-1" class="headerlink" title="实际应用"></a>实际应用</h2><p>书上的是个击鼓传花的小游戏。原理就是循环到相应位置时，队列弹出那个元素。最后留下的就是赢家。<br>源代码如下:<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 击鼓传花的小游戏</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span>  &#123;Array&#125;  nameList 参与人员列表</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span>  &#123;Number&#125; num      在循环中要被弹出的位置</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> &#123;String&#125;          返回赢家(也就是最后活下来的那个)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">hotPotato</span><span class="params">(nameList, num)</span> </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> queue = <span class="keyword">new</span> Queue();</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; nameList.length; i++) &#123;</span><br><span class="line">    queue.enqueue(nameList[i]);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> eliminated = <span class="string">''</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">while</span> (queue.size() &gt; <span class="number">1</span>) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; num; i++) &#123;</span><br><span class="line">      queue.enqueue(queue.dequeue());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    eliminated = queue.dequeue();</span><br><span class="line">    console.log(eliminated + <span class="string">" Get out!"</span>)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> queue.dequeue()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/数据结构/" rel="tag"># 数据结构</a>
          
            <a href="/blog/tags/算法/" rel="tag"># 算法</a>
          
            <a href="/blog/tags/栈与队列/" rel="tag"># 栈与队列</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/09/23/TypeScript-不止稳，而且快/" rel="next" title="TypeScript - 不止稳，而且快">
                <i class="fa fa-chevron-left"></i> TypeScript - 不止稳，而且快
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/09/23/javascript之数组操作/" rel="prev" title="javascript之数组操作">
                javascript之数组操作 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">lhweb</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">39</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">25</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#学习起因"><span class="nav-number">1.</span> <span class="nav-text">学习起因</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#栈"><span class="nav-number">2.</span> <span class="nav-text">栈</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#JavaScipt中栈的实现"><span class="nav-number">2.1.</span> <span class="nav-text">JavaScipt中栈的实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#push方法的实现"><span class="nav-number">2.1.1.</span> <span class="nav-text">push方法的实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#pop方法的实现"><span class="nav-number">2.1.2.</span> <span class="nav-text">pop方法的实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#peek方法的实现"><span class="nav-number">2.1.3.</span> <span class="nav-text">peek方法的实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#其余方法的实现"><span class="nav-number">2.1.4.</span> <span class="nav-text">其余方法的实现</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实际应用"><span class="nav-number">2.2.</span> <span class="nav-text">实际应用</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#队列"><span class="nav-number">3.</span> <span class="nav-text">队列</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#JavaScipt中队列的实现"><span class="nav-number">3.1.</span> <span class="nav-text">JavaScipt中队列的实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#enqueue方法的实现"><span class="nav-number">3.1.1.</span> <span class="nav-text">enqueue方法的实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#dequeue方法的实现"><span class="nav-number">3.1.2.</span> <span class="nav-text">dequeue方法的实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#front方法的实现"><span class="nav-number">3.1.3.</span> <span class="nav-text">front方法的实现</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实际应用-1"><span class="nav-number">3.2.</span> <span class="nav-text">实际应用</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">lhweb</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
